/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.user.server.impl;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.jb.user.client.LoginException;
import org.jb.user.client.rpc.UserService;
import org.jb.user.server.UserRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.servlet.SessionScoped;

/**
 * 
 * @author jeremie
 *
 */
@SessionScoped
public class UserServiceImpl implements UserService, HttpSessionBindingListener {

	private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	private String user = null;
	private final UserRegistry registry;
	private final HashService hashService;
	private final Cookies cookies;
	
	/**
	 * 
	 * @param registry
	 */
	@Inject
	public UserServiceImpl( UserRegistry registry, HashService hashService, Cookies cookies ) {
		this.registry = registry;
		this.hashService = hashService;
		this.cookies = cookies;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.user.client.rpc.UserService#autologin()
	 */
	@Override
	public String autologin() throws LoginException {
		logger.debug("Autologing...");
		
		if (user != null) {
			logger.info("Autologing ok with user u={}", user );
			return user;
		}
		
		String cookieUser = cookies.getUserCookie();
		if (cookieUser != null) {
			String cookiePassword = cookies.getPasswordCookie();
			
			logger.debug("Logging with permanent cookie, user={}", cookieUser );

			registry.checkLogin(cookieUser, cookiePassword );
			
			logger.debug("Logged with permanent cookie, user={}", cookieUser );
			cookies.setUserPasswordCookies(cookieUser, cookiePassword );

			user = cookieUser;
			return user;
		}
		
		throw new LoginException();
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.client.user.UserService#connect(java.lang.String, java.lang.String)
	 */
	@Override
	public String connect(String name, String password) throws LoginException {
		
		if (name == null) {
			throw new IllegalArgumentException("name is null");
		}
		
		String hashValue = hashService.getHashedValue(password);
		registry.checkLogin(name, hashValue );
		
		logger.info("Logging with user={}", name );
		
		user = name;
		cookies.setUserPasswordCookies(user, hashValue );
		
		return user;
	}

	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.client.user.UserService#disconnect()
	 */
	@Override
	public void disconnect() {
		user = null;
		cookies.invalidate();
	}

	/*
	 * (non-Javadoc)
	 * @see com.google.inject.Provider#get()
	 */
	public String getUser() {
		return user;
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent)
	 */
	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		logger.debug("Session bound");
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent)
	 */
	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		if (user != null) {
			logger.debug("session unbound {}", user );
			
			registry.removeLogin(user);
		}	
	}
}
